package com.mhwx.mhlive.ui.base;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiansong on 2015/5/14.
 */
public class BaseAdapter<T> extends android.widget.BaseAdapter{

    protected ViewGroup parent;

    protected List<T> mItems = new ArrayList<T>();

    public BaseAdapter() {
    }

    public BaseAdapter(List<T> list) {
        if (list != null)
            addItems(list);
    }

    public void addItems(List<T> items) {
        mItems.addAll(items);
        notifyDataSetChanged();
    }

    public void refreshItems(List<T> items) {
        mItems.clear();
        mItems.addAll(items);
        notifyDataSetChanged();
    }

    public void remove(T item){
        mItems.remove(item);
        notifyDataSetChanged();
    }

    public boolean containsAll(List<T> items){
        return mItems.containsAll(items);
    }

    public void updateView(int id, T item) {
        mItems.set(id, item);
        if (parent != null && parent instanceof AdapterView) {
            AdapterView<?> view = ((AdapterView<?>) parent);
            int firstP = view.getFirstVisiblePosition();
            int lastP = view.getLastVisiblePosition();
            if (firstP <= id && id <= lastP) {
                getView(id, parent.getChildAt(id - firstP), parent);
            }
        } else
            notifyDataSetChanged();
    }

    public ViewGroup setParent(ViewGroup parent) {
        return this.parent = parent;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return null;
    }

    @Override
    public int getCount() {
        return mItems == null ? 0 : mItems.size();
    }

    @Override
    public T getItem(int location) {
        return mItems.get(location);
    }

    @Override
    public long getItemId(int id) {
        return id;
    }
}
